<?php

namespace Home\Controller;
use Think\Controller;


class DefaultController extends Controller {
    
    /**
     * 手机动态码
     * @param type $param
     */
    public function generate_phone_random($len)
    {
        $arrray = range(0, 9);
        $random = '';
        for ($i = 0; $i < $len; $i++) {
            $random .= $arrray[mt_rand(0, 9)];
        }
        return $random;
    }
    
    /**
     * 验证手机动态码
     * 
     * @param type $phone
     * @param type $type 1:注册，2:找回密码
     * @param type $salt
     * @return array('flag','content')
     */
    public function check_phone_salt($phone, $type, $salt)
    {   
        $verify = array('phone' => $phone, 'type' => $type, 'salt' => $salt);
        $sms = M('sms_record');
        $salt_info = $sms->where($verify)->find();
        $result = array();
        if ($salt_info['times'] >= 5) {
            $result['flag'] = 3;
            $result['content'] = '该动态码验证次数超过限制';
        } elseif ($salt_info['is_used'] == 1) {
            $result['flag'] = 4;
            $result['content'] = '该动态码已被验证';
        } elseif ($salt_info['salt'] != $salt) {
            $update['times'] = $salt_info['times']+1;
            $update['id'] = $salt_info['id'];
            $sms->save($update);
            //验证次数加1
            $result['flag'] = 2;
            $result['content'] = '动态码不正确';
        } elseif (time() - $salt_info['happen_time'] > 1800) {
            $result['flag'] = 5;
            $result['content'] = '验证超时';
        } else {
            $result['flag'] = 1;
            $result['content'] = '验证成功';
            $used['is_used'] = 1;
            $used['id'] = $salt_info['id'];
            $sms->save($used);
        }
        
        return $result;
        /*$result['flag'] = 1;
        $result['content'] = '验证成功';
        return $result;*/
    }
    
    public function session(){
        if(session('phone')){
            $this->redirect('/Home/Index/index');
        }
    }
    
    public function judgePatriarch(){
        if(session('phone') && session('type') != 2){
           echo " <script language='javascript'> 
            alert('Hey, you are not a parent'); 
            window.history.back(-1); 
            </script> ";
            
        }elseif(!session('phone') || session('type') != 2){
            $this->redirect('/Home/Index/login');
        }
    }
    
    public function orderSn(){
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
    
    public function judgePhone($phone){
        if (!preg_match("/1[3458]{1}\d{9}$/", $phone)) {
            return false;
        }else{
            return true;
        }
    }
    
    
    public function lesson($data, $class){
        $lesson = require_once "./Application/Pub/Dictionaries/".$class.".php";
        $new_lesson = '';
        if(is_array($data)){            
            foreach($data as $k  => $v){
                $new_lesson .= "<span class='label label-info btn-info' style='margin-right:10px;'>".$lesson[$v]."</span>";
            }
        }else{
            $new_lesson = $lesson[$data];
        }
        return $new_lesson;
    }
    


    function sendSMS($mobile, $code)
    {
        $http = 'http://api.sms.cn/mt/';		//短信接口
        $uid = 'ychezhe';							//用户账号
        $pwd = '898989';							//密码
        $mobile	 = trim($mobile);	//号码
        $mobileids	 = '';	//号码唯一编号
        $content = iconv("UTF-8","GB2312//IGNORE","【超老师】中国科技大学唯一官方家教平台，您的验证码为".$code);

        $data = array
            (
            'uid'=>$uid,					//用户账号
            'pwd'=>md5($pwd.$uid),			//MD5位32密码,密码和用户名拼接字符
            'mobile'=>$mobile,				//号码
            'content'=>$content,			//内容
            'mobileids'=>$mobileids,		//发送唯一编号
            );

        $re= $this->postSMS($http,$data);			//POST方式提交

        //$re = getSMS($url,$data='');		//GET方式提交

        if( strstr($re,'stat=100'))
        {
                return "发送成功!";
        }
        else if( strstr($re,'stat=101'))
        {
                return "验证失败! 状态：".$re;
        }
        else 
        {
                return "发送失败! 状态：".$re;
        }
    }

    function sendSMSContent($mobile, $content)
    {
        /*$cache_dir = $_SERVER['DOCUMENT_ROOT'].'/data/cache/';
        $cache_file = $cache_dir.'userFund.data';
        if (!is_dir($cache_dir)) {
            $fp = mkdir($cache_dir,0744,true);
        }
        if (!file_exists($cache_file)) {
            $fp = fopen($cache_file, 'w+');
            fclose($fp);
        }
        file_put_contents($cache_file, $mobile."\n".$content."\n\n", FILE_APPEND);//对文件后追加文件*/
        $http = 'http://api.sms.cn/mt/';		//短信接口
        $uid = 'ychezhe';						//用户账号
        $pwd = '898989';						//密码
        $mobile	 = trim($mobile);	            //号码
        $mobileids	 = '';	                    //号码唯一编号
        $content = iconv("UTF-8","GB2312//IGNORE",$content."--科大官方唯一家教平台超老师");

        $data = array
        (
            'uid'=>$uid,					//用户账号
            'pwd'=>md5($pwd.$uid),			//MD5位32密码,密码和用户名拼接字符
            'mobile'=>$mobile,				//号码
            'content'=>$content,			//内容
            'mobileids'=>$mobileids,		//发送唯一编号
        );

        $re= $this->postSMS($http,$data);			//POST方式提交

        //$re = getSMS($url,$data='');		//GET方式提交

        if( strstr($re,'stat=100'))
        {
            return "发送成功!";
        }
        else if( strstr($re,'stat=101'))
        {
            return "验证失败! 状态：".$re;
        }
        else
        {
            return "发送失败! 状态：".$re;
        }
    }
//POST方式
function postSMS($url,$data='')
{
	$row = parse_url($url);
	$host = $row['host'];
	$port = $row['port'] ? $row['port']:80;
	$file = $row['path'];
	while (list($k,$v) = each($data)) 
	{
		$post .= rawurlencode($k)."=".rawurlencode($v)."&";	//转URL标准码
	}
	$post = substr( $post , 0 , -1 );
	$len = strlen($post);
	$fp = @fsockopen( $host ,$port, $errno, $errstr, 10);
	if (!$fp) {
		return "$errstr ($errno)\n";
	} else {
		$receive = '';
		$out = "POST $file HTTP/1.1\r\n";
		$out .= "Host: $host\r\n";
		$out .= "Content-type: application/x-www-form-urlencoded\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Content-Length: $len\r\n\r\n";
		$out .= $post;		
		fwrite($fp, $out);
		while (!feof($fp)) {
			$receive .= fgets($fp, 128);
		}
		fclose($fp);
		$receive = explode("\r\n\r\n",$receive);
		unset($receive[0]);
		return implode("",$receive);
	}
}
    
    
    
}

